package spider;


import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 获得用户ip 得到城市  直接绑定到数据库 的cityId
 *
 * @author Khai Loon
 * @version 2017/3/22 0022 下午 2:35
 */
public class IpUtils {

    /**
     * 测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
       /* for (int i =0;i<=100;i++){
            System.out.println(getCity("14.111.48.106"));
        }*/
        String a = "本站数据：重庆市重庆市电信";

        System.out.println(a.substring(a.indexOf("：") + 1, a.length()));
    }

    public static int getCity(HttpServletRequest request) {
        String ip = getIp4(request);
        if (ip.contains("127.0.0.1") || ip.contains("localhost") || ip.contains("192.168.")) {
            return 554873;
        }
        String cityNames = getCity(ip)==null?"":"";
        int cityId = 554873;
        if (cityNames.contains("重庆")) {
            cityId = 554873;
        } else if (cityNames.contains("成都")) {
            cityId = 566974;
        }
        return cityId;
    }

    public static String getCityByMonile(String monile) {
        Document doc = null;
        try {
            doc = Jsoup.connect("http://www.ip138.com:8080/search.asp?mobile=" + monile + "&action=mobile").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String v = doc.select("tr:contains(卡号归属地)>td:eq(1)").text();
        if (StringUtils.isNotBlank(v)) {
            v = StringUtils.deleteWhitespace(v).replaceAll(" ","");
        }
        return v;
    }

    public static String getCity(String ip) {
        Document doc = null;
        try {
            doc = Jsoup.connect("http://www.ip138.com/ips1388.asp?ip=" + ip + "&action=2").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc.select("td>ul:contains(本站数据)>li:eq(0)").text();
    }

    public static String getIp4(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
}
